<?php

/**
 * 宣教表
 */

namespace app\common\model;

use think\Paginator;
use think\facade\Cache;
use catcher\exceptions\FailedException;
use catchAdmin\permissions\model\Users as UsersModel;
use app\common\model\search\PropagandaEducationSearch;
use app\common\model\PropagandaEducationClass as ClassModel;

class PropagandaEducation extends BaseModel
{
    use PropagandaEducationSearch;

    protected $name = "propaganda_education";

    /**
     * 获取数据列表
     */
    public function getList()
	{
        $users = $this->getUserIds();
        $depts = $this->getDeptListByUser(0);

        $userWhere = [];
        if (!empty($users)) {
            $userWhere[] = ['creator_id', 'in', $users];
        }

        $deptWhere = [];
        if (!empty($depts)) {
            $deptWhere[] = ['apply_department.value', 'in', $depts];
        }

        return $this->mongoSearch()
            ->whereOr($userWhere)
            ->whereOr($deptWhere)
            ->order('created_at', 'desc')
            ->paginate($this->pageLimit)
            ->each(function($item, $key){
                $item['creator_name'] = UsersModel::where('id', $item['creator_id'])->value('username');
                return $item;
            });
	}

    /**
     * 添加数据
     * @param array $data
     * @return string
     */
    public function addData(array $data): string
    {
        //添加时销毁自带的主键id
        unset($data['id']);
        return $this->save($data);
    }

    /**
     * 更新数据
     * @param string $id
     * @param array $data
     * @return bool
     */
    public function saveData($id, array $data): bool
    {
        $model = self::find($id);
        $data['deleted_at'] = (int)$data['deleted_at'];
        $data['department_id'] = request()->user()->department_id;
        return $model->save($data);
    }

    /**
     * 获取详情
     * @param string $id
     * @return object
     */
    public function getDetail($id): object
	{
		return $this->where('id', $id)->find();
	}

    /**
     * 宣教树型
     */
    public function getDatas()
    {
        $depts = $this->getDeptListByUser(0);

        $userWhere = [];
        if (!empty($users)) {
            $userWhere[] = ['creator_id', 'in', $this->getUserIds()];
        }

        $deptWhere = [];
        if (!empty($depts)) {
            $deptWhere[] = ['apply_department.value', 'in', $depts];
        }

        //获取宣教分类
        $edClass = (new ClassModel())->where('isopen', 1)->field('id,name')->select()->toArray();

        //获取宣教课程
        $edCourse = $this->where('isopen', '=', 1)
                         ->whereOr($userWhere)
                         ->whereOr($deptWhere)
                         ->field('id,name,classify')
                         ->select()
                         ->toArray();

        $newData = [];
        foreach ($edClass as $key => $val) {
            $newData[$key]['id'] = $val['id'];
            $newData[$key]['name'] = $val['name'];
            $newData[$key]['parent_id'] = 0;
            $newData[$key]['children'] = [];
            foreach ($edCourse as $k1 => $v1) {
                foreach ($v1['classify'] as $k2 => $v2) {
                    if ($val['id'] === $v2['value']) {
                        $newData[$key]['children'][] = [
                            'id' => $v1['id'],
                            'name' => $v1['name'],
                            'parent_id' => $val['id'],
                        ];
                    }
                }
            }
        }
        return $newData;
    }

    /**
     * 根据分类id获取宣教
     * @param string $classify 分类id
     * @return Paginator
     */
    public function getEdDatas(string $classify): Paginator
    {
        $where['isopen'] = 1;
        $where['classify.value'] = $classify;
        return $this->mongoSearch()
                    ->where($where)
                    ->field('id,cover.url,name,updated_at')
                    ->paginate($this->pageLimit)
                    ->each(function($item, $key){
                        $hits = Cache::store('redis')->get('ed:'.(string)$item['id']);
                        $item['hits'] = $hits?(int)$hits:0;
                        return $item;
                    });
    }

    /**
     * 获取健康养生分类宣教
     * @param int $type 1 更多，2 首页
     */
    public function getJkysDatas($type = 1)
    {
        if ($type == 1)
        {
            return $this->where('classify.value', '6357338578cede199c1927b2')
                    ->field('id,cover.url,name,describe,updated_at')
                    ->order('created_at', 'desc')
                    ->paginate($this->pageLimit)
                    ->each(function($item, $key){
                        $hits = Cache::store('redis')->get('ed:'.(string)$item['id']);
                        $item['describe'] = isset($item['describe'])?$item['describe']:"";
                        $item['hits'] = $hits?(int)$hits:0;
                        return $item;
                    });
        }else{
            return $this->where('classify.value', '6357338578cede199c1927b2')
                    ->field('id,cover.url,name,describe,updated_at')
                    ->order('created_at', 'desc')
                    ->limit(3)
                    ->select()
                    ->each(function($item, $key){
                        $hits = Cache::store('redis')->get('ed:'.(string)$item['id']);
                        $item['describe'] = $item['describe']??'';
                        $item['hits'] = $hits?(int)$hits:0;
                        return $item;
                    })
                    ->toArray();
        }
    }

    /**
     * 患者端获取详情
     * @param string $ed_id 宣教id
     */
    public function getHzDetail(string $ed_id)
	{
        $row = $this->where('id', $ed_id)->find();
        if (!isset($row) || empty($row))
        {
            throw new FailedException("宣教信息不存在");
        }

        //标记已读
        $model = self::find($ed_id);
        $model->save(['isview' => 1]);

        //浏览量+1
        Cache::store('redis')->incr('ed:'.$row['id']);
		return $row;
	}
}